package com.customization.test.demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.*;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.json.JSONUtil;
import weaver.general.Util;

public class HttpUtils {

    private static final Log log = LogFactory.getLog(HttpUtils.class);

    /**
     * 第二步：
     * 通过第一步中注册系统返回信息进行获取token信息
     */
    public static Map<String,Object> Getoken(String address) throws Exception {
        // 从系统缓存或者数据库中获取ECOLOGY系统公钥和Secret信息
        String SERVER_SECRET = "62a6ff58-e759-447c-99df-130d5cc2168c";
        String SERVER_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApjMw2mKiMasELmLsAkILnUeYNDLcCeZ4c40952NFr5ERx8GbU4fk9Td4M6KtT+GmOm/C2XI8jPjTiXPnarRIvyrZnI/6e5Fanu+D+Rn1QKHILhynz2GBYLrjGVC8xf6LfK18GzbrEPetJ90fnyRXstJdu8QcxO4oQxb74AHPT6TmbljTLPRKcnc001ezrppdUBVwhxQQMjBBm8BKi403fiOCV/Y0mJoXBndZMv7JXOANirw/pw0k5t+U8AVLh/a+4EwjM2zf4w3dheu6toBPOkmwmDwCjBhKeK6GPToTQpa2kcwt9NsRmj/yfXilHo3KSZzYyCBPBAEwvtbIjVe6OQIDAQAB";

        // 公钥加密,所以RSA对象私钥为null
        RSA rsa = new RSA(null,SERVER_PUBLIC_KEY);
        //对秘钥进行加密传输，防止篡改数据
        String encryptSecret = rsa.encryptBase64(SERVER_SECRET,CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);

        Map<String, Object> header = new HashMap<>();
        header.put("appid",APPID);
        header.put("secret",encryptSecret);
        // 为Token缓存设置过期时间
        header.put("time","3600");
        header.put("Content-Type","application/json;charset=UTF-8");
        // 调用ECOLOGY系统接口进行注册
        String data = doPost(address+ "/api/ec/dev/auth/applytoken",header,null,null,null,true);
        Map<String,Object> datas = JSONUtil.parseObj(data);
        System.out.println("token()："+StrUtil.nullToEmpty((String)datas.get("token")));
        return datas;
    }


    /**
     * get请求
     * @param url  请求地址
     * @param headers 请求头参数
     * @return
     */
    public static String doGet(String url, Map<String,Object> headers, String encode, String decode) throws Exception {
        if(encode == null){
            encode = "utf-8";
        }
        if(decode == null){
            decode = "utf-8";
        }
        CloseableHttpClient client= null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
            if (headers != null && !headers.isEmpty()) {
                for (String s : headers.keySet()) {
                    httpGet.setHeader(s, headers.get(s).toString());
                }
            }
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);
            return new String(jsons.getBytes(decode),encode);
        } finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭get-response请求出错："+e.toString());
            }
            try {
                if(client != null){
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭get-client请求出错："+e.toString());
            }
        }
    }

    /**
     * post请求
     *
     * @param url
     * @param headers 请求头
     * @param params  请求数据
     * @return 响应数据
     */
    public static String doPost(String url, Map<String,Object>  headers, JSONObject  params, String encode, String decode,boolean isJson) throws Exception {
        if(encode == null){
            encode = "utf-8";
        }
        if(decode == null){
            decode = "utf-8";
        }
        CloseableHttpClient client= null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);

            if(headers != null){
                for (String s : headers.keySet()) {
                    httpPost.setHeader(s, headers.get(s).toString());
                }
            }

            if(params != null){
                if(isJson) {
                    String jsonStr = JSONObject.toJSONString(params);
                    StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8");
                    httpPost.setEntity(stringEntity);
                }else {
                    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    for (Object key : params.keySet()) {
                        String keyStr = key.toString();
                        builder.addPart(keyStr, new StringBody(params.get(keyStr) + "", ContentType.create("text/plain", Consts.UTF_8)));
                    }

                    HttpEntity reqEntity = builder.build();
                    httpPost.setEntity(reqEntity);
                }
            }

            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);
            return new String(jsons.getBytes(decode),encode);
        } finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭post-response请求出错："+e.toString());
            }
            try {
                if(client != null){
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭post-client请求出错："+e.toString());
            }
        }
    }

    /**
     * 发起PUT同步请求
     *
     * @param url
     * @param headers 请求头
     * @param params  请求数据
     * @return 响应数据
     *
     */
    public static String doPut(String url,Map<String,Object> headers, Map<String,Object> params, String encode, String decode) throws Exception {
        if(encode == null){
            encode = "utf-8";
        }
        if(decode == null){
            decode = "utf-8";
        }
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpPut httpPut = new HttpPut(url);
            httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");
            if(headers != null){
                for (String s : headers.keySet()) {
                    httpPut.setHeader(s, headers.get(s).toString());
                }
            }
            if(params != null){
                String jsonStr = JSONObject.toJSONString(params);
                StringEntity stringEntity = new StringEntity(jsonStr,"UTF-8");
                httpPut.setEntity(stringEntity);
            }
            response = client.execute(httpPut);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);
            return new String(jsons.getBytes(decode),encode);
        } finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭put-response请求出错："+e.toString());
            }
            try {
                if(client != null){
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭put-client请求出错："+e.toString());
            }
        }
    }

    /**
     * delete请求
     *
     * @param url
     * @param headers
     * @param encode
     * @return
     */
    public static String doDelete(String url, Map<String,Object> headers, String encode, String decode) throws Exception {
        if(encode == null){
            encode = "utf-8";
        }
        if(decode == null){
            decode = "utf-8";
        }
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClientBuilder.create().build();
            HttpDelete httpDelete = new HttpDelete(url);
            //设置header
            if (headers != null && !headers.isEmpty()) {
                for (String s : headers.keySet()) {
                    httpDelete.setHeader(s, headers.get(s).toString());
                }
            }

            response = client.execute(httpDelete);
            HttpEntity entity = response.getEntity();
            String jsons = EntityUtils.toString(entity);
            return new String(jsons.getBytes(decode),encode);
        } finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                log.error("关闭delete-response同步请求出错："+e.toString());
            }
            try {
                if(client != null){
                    client.close();
                }
            } catch (IOException e) {
                log.error("关闭delete-client同步请求出错："+e.toString());
            }
        }
    }


    /**
     * 模拟缓存服务
     */
    private static final Map<String,String> SYSTEM_CACHE = new HashMap <>();
    /**
     * ecology系统发放的授权许可证(appid)
     */
    private static final String APPID = "8B45A195-Z124-4D03-2AC2-6935SDA98";//8B45A195-B28C-4D03-2AC2-7BFF330EC8q2";

    // INSERT INTO ECOLOGY_BIZ_EC(ID,APPID,NAME) VALUES('2','8B45A195-Z124-4D03-2AC2-6935SDA98','上海泛微网络科技股份有限公司');
    /**
     * 第一步：
     *
     * 调用ecology注册接口,根据appid进行注册,将返回服务端公钥和Secret信息
     */
    public static Map<String,Object> testRegist(String address) throws Exception {
        // 获取当前系统RSA加密的公钥
        RSA rsa = new RSA();
        String publicKey = rsa.getPublicKeyBase64();
        String privateKey = rsa.getPrivateKeyBase64();

        // 客户端RSA私钥
        SYSTEM_CACHE.put("LOCAL_PRIVATE_KEY",privateKey);
        // 客户端RSA公钥
        SYSTEM_CACHE.put("LOCAL_PUBLIC_KEY",publicKey);
        //调用ECOLOGY系统接口进行注册
        Map<String, Object> header = new HashMap<>();
        header.put("appid",APPID);
        header.put("cpk",publicKey);
        header.put("Content-Type","application/json;charset=UTF-8");
        Map<String, Object> params = new HashMap<>();
        String data = doPost(address + "/api/ec/dev/auth/regist",header,null,null,null,true);
        // 打印ECOLOGY响应信息
        System.out.println("testRegist()："+data);
        Map<String,Object> datas = JSONUtil.parseObj(data);
        //ECOLOGY返回的系统公钥
        SYSTEM_CACHE.put("SERVER_PUBLIC_KEY",StrUtil.nullToEmpty((String)datas.get("spk")));
        //ECOLOGY返回的系统密钥
        SYSTEM_CACHE.put("SERVER_SECRET",StrUtil.nullToEmpty((String)datas.get("secrit")));
        return datas;
    }

    /**
     * 第二步：
     * 通过第一步中注册系统返回信息进行获取token信息
     */
    public static Map<String,Object> testGetoken(String address) throws Exception {
        // 从系统缓存或者数据库中获取ECOLOGY系统公钥和Secret信息
        String secret = SYSTEM_CACHE.get("SERVER_SECRET");
        String spk = SYSTEM_CACHE.get("SERVER_PUBLIC_KEY");

        // 公钥加密,所以RSA对象私钥为null
        RSA rsa = new RSA(null,spk);
        //对秘钥进行加密传输，防止篡改数据
        String encryptSecret = rsa.encryptBase64(secret,CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);

        Map<String, Object> header = new HashMap<>();
        header.put("appid",APPID);
        header.put("secret",encryptSecret);
        // TODO 为Token缓存设置过期时间
        header.put("time","3600");
        header.put("Content-Type","application/json;charset=UTF-8");
        // 调用ECOLOGY系统接口进行注册
        String data = doPost(address+ "/api/ec/dev/auth/applytoken",header,null,null,null,true);
        Map<String,Object> datas = JSONUtil.parseObj(data);
        System.out.println("encryptSecret()："+encryptSecret);
        System.out.println("token()："+StrUtil.nullToEmpty((String)datas.get("token")));
        //ECOLOGY返回的token
        SYSTEM_CACHE.put("SERVER_TOKEN",StrUtil.nullToEmpty((String)datas.get("token")));
        return datas;
    }

    /**
     * 第三步：
     * 调用ecology系统的rest接口，请求头部带上token和用户标识认证信息
     * @param address ecology系统地址
     * @param api rest api 接口地址(该测试代码仅支持GET请求)
     * @param jsonParams 请求参数json串
     *
     * 注意：ECOLOGY系统所有POST接口调用请求头请设置 "Content-Type","application/x-www-form-urlencoded; charset=utf-8"
     */
    public static String testRestful(String address,String api,String jsonParams) throws Exception {
        //ECOLOGY返回的token
        String token= SYSTEM_CACHE.get("SERVER_TOKEN");
        if (StrUtil.isEmpty(token)){
            token = (String) testGetoken(address).get("token");
        }
        String spk = SYSTEM_CACHE.get("SERVER_PUBLIC_KEY");
        //封装请求头参数
        RSA rsa = new RSA(null,spk);
        //对用户信息进行加密传输,暂仅支持传输OA用户ID
        String encryptUserid = rsa.encryptBase64("1",CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);
        System.out.println("encryptUserid:"+encryptUserid);

        Map<String, Object> header = new HashMap<>();
        header.put("appid",APPID);
        header.put("token",token);
        header.put("userid",encryptUserid);
//        header.put("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
        header.put("Content-Type","application/json;charset=UTF-8");

        JSONObject params = new JSONObject();
        params.put("key","q");


        String data = doPost(address+ api+"?key=user",header,params,null,null,true);
//        String data = doGet(address+ api,header,null,null);
        System.out.println("testRestful()："+data);
        return data;
    }

    public static void main(String[] args) {
        // MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4w4jM9Kq9Wrfe/oEp+ztriznhqTfp6MOveecc04gI/sgAXvaOYgiRoxDFlXoorgqm7fxMxrs+Z8993f3l0hf69yu7a/N3YYMMP+qXWq2PIKkFkIzWgh1sos7tuECZEI7FTUuKtNjQNPXddzTX2fFNqxj2UVCnUAl3kO820NuCClKfxBQ9TAD0qD8lR6aVdnyWtvxe+ZmooZdOTLcxQltwB7qDsEegi0nL9mwYO+62AkT3DeCCho/4VA0YEpIOzqeSWLeQPKmGJtE0ZNHqbVDSo2Rkpb+VJVlqIdqL2Mo2vxZSTRrOJyF/Thiaq/+1YRDJG0rs+sQ55QACTGA1d+b4wIDAQAB
        /**
         * encryptSecret()：C3WVxYyrluKvFLjGDPuopD0OEvp2dBOvaCpGmOHA5xDPo2fny4BnXnEhv8rLWEzRj6QzKz7OLFIg5t5EsJ9Yxt+PgUXDxwajs/65EONpSRgOoA/bg7RAWSlEIJPb1zEIsrnwvQN+57ZWuloXep7z3yD8j9KX59lUz6OXarN5tccNeVIqca3/yGdNHFsTGe8aUwQpkRYVRtuVGKyd8JIdNMB9eY/nMtz/LZ3q3dl6mrt6vq3R1V/dV+kzdSYGTZI6wCeqNCs5hTGepKHf6srzzXw8jVR+icqHUaa/zOzpVUKPRIRiD9cMSJnnVaHsBULRme8otcCXGyyF0y7vK2DUtQ==
         * token()：7d44263d-3edd-4306-90f5-4ec9854b2767
         * 获取token--》SERVER_PUBLIC_KEY：MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4w4jM9Kq9Wrfe/oEp+ztriznhqTfp6MOveecc04gI/sgAXvaOYgiRoxDFlXoorgqm7fxMxrs+Z8993f3l0hf69yu7a/N3YYMMP+qXWq2PIKkFkIzWgh1sos7tuECZEI7FTUuKtNjQNPXddzTX2fFNqxj2UVCnUAl3kO820NuCClKfxBQ9TAD0qD8lR6aVdnyWtvxe+ZmooZdOTLcxQltwB7qDsEegi0nL9mwYO+62AkT3DeCCho/4VA0YEpIOzqeSWLeQPKmGJtE0ZNHqbVDSo2Rkpb+VJVlqIdqL2Mo2vxZSTRrOJyF/Thiaq/+1YRDJG0rs+sQ55QACTGA1d+b4wIDAQAB
         * 获取token--》LOCAL_PRIVATE_KEY：MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALOys0KtaZn5B3yHG0gUuubndU/7YvScwd9onfRvOCBN6URHKda3D4vyyYOu2d1D/OHjyqKLtd8VoNfYXOE0Heo4www1GaO7os9GsCXKS5trbpHspCI5hXsFt0AufcJucrHLtrnb8laRGRL0DDVUqd9nQkckjHA0nTDbsz0M9WtzAgMBAAECgYAKuURXW0/s/16CAPIQ2CPbOb7XehIKtPwg3/ZlKun3i467I2AMzznfSSrbb+jSeocx18007A97c6f4mZHZYqnSQdnY8FCY6UzSqINt8dkTsxC0afXCWDLvEd/oLe70rgx/6azlQ8PNTQN3KvNLrudKnKwPUrIaPTU08HcF85O8CQJBAN28EbtF58+TD7BjVCXjtpNYSxJsXqme5vwqQKqBOhg7TMcMyhyxCYzM7TXFHARiS6IFQyjsgCBR1N8yc4EPDnUCQQDPd6SFYLZdcwxpMeLnkAxe1dYXzQzPgY+6zui/R/ayK77xoOhOqmtmkBRN/Vp+wVucewDKorD1gCxKRIpGu6VHAkALEgCwoOTZ8DWwUMU6vwu2f4n/+XkgbtaJcHKaEKmd3BgROAo/NHeNmA2fyZ+EeIPeKvUXbfdXpb5DBnnNz7qhAkEAvKG4mXikdvT67M5p00caqENepEdQhX70ctJbtkc1GyxBMSqu7Y9vlVIc1Agt9p/RrsX7o0InCSAfpOsKmmNUUwJAZh2obiXG7Wo8jB73t936AFYw+r5gplKsJa90UzRJs0DeGLDglmhcVI18R+Xu7dc5b1ywna1L9wSJtajBBB7lLA==
         * 获取token--》SERVER_SECRET：72cd54bc-c8ad-4e1c-8a42-f5411fb0e632
         * 获取token--》LOCAL_PUBLIC_KEY：MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzsrNCrWmZ+Qd8hxtIFLrm53VP+2L0nMHfaJ30bzggTelERynWtw+L8smDrtndQ/zh48qii7XfFaDX2FzhNB3qOMMMNRmju6LPRrAlykuba26R7KQiOYV7BbdALn3CbnKxy7a52/JWkRkS9Aw1VKnfZ0JHJIxwNJ0w27M9DPVrcwIDAQAB
         * 获取token--》SERVER_TOKEN：7d44263d-3edd-4306-90f5-4ec9854b2767
         */


        try {
//            SYSTEM_CACHE.put("SERVER_SECRET","4a32badf-458f-4536-b021-cb5279419761");
//            SYSTEM_CACHE.put("SERVER_PUBLIC_KEY","MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApiyBn2k8cvWrIeGBxTiWO1gitGh6jen0ubbXhsagAK6XzwKheUgFYWu8WEhSoUNaibv0GPFptrrK4M82nC/1zOtp9N4ZVi63GhTKHrPDBNbBJ/0WkxELVRCCeSozRJELoN5VWck6vAyA3STLNLe+sLP7Q/XXBFXcb+ya3C0NB6EcghSHo1a0NRrXowWBx7TIcGlkzsGbbtIA0I66nTwyOncixOktkalAcaNeMuRcgKnCXMmCFYj4JWaa724hLf4v7zrMlaBzeS0a5Osxb/6l0QTpr1+jU2/K8VS7rHv+YxgK2e0XzlmZWkF55sEc4jGj17Nc9GLWptlBrHEw5K1MKQIDAQAB");
//            SYSTEM_CACHE.put("SERVER_SECRET","72cd54bc-c8ad-4e1c-8a42-f5411fb0e632");
//            SYSTEM_CACHE.put("SERVER_PUBLIC_KEY","MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4w4jM9Kq9Wrfe/oEp+ztriznhqTfp6MOveecc04gI/sgAXvaOYgiRoxDFlXoorgqm7fxMxrs+Z8993f3l0hf69yu7a/N3YYMMP+qXWq2PIKkFkIzWgh1sos7tuECZEI7FTUuKtNjQNPXddzTX2fFNqxj2UVCnUAl3kO820NuCClKfxBQ9TAD0qD8lR6aVdnyWtvxe+ZmooZdOTLcxQltwB7qDsEegi0nL9mwYO+62AkT3DeCCho/4VA0YEpIOzqeSWLeQPKmGJtE0ZNHqbVDSo2Rkpb+VJVlqIdqL2Mo2vxZSTRrOJyF/Thiaq/+1YRDJG0rs+sQ55QACTGA1d+b4wIDAQAB");
//

//            Map<String, Object> regist = testRegist("https://bpm-dev.myxjp.com");
//            for (String key : SYSTEM_CACHE.keySet()) {
//                System.out.println("注册--》"+key +"："+SYSTEM_CACHE.get(key));
//            }
//            Map<String, Object> token = testGetoken("https://bpm-dev.myxjp.com");
//            for (String key : SYSTEM_CACHE.keySet()) {
//                System.out.println("获取token--》"+key +"："+SYSTEM_CACHE.get(key));
//            }

//            String spk = SYSTEM_CACHE.get("SERVER_PUBLIC_KEY");
//            //封装请求头参数
//            RSA rsa = new RSA(null,spk);
//            //对用户信息进行加密传输,暂仅支持传输OA用户ID
//            String encryptUserid = rsa.encryptBase64("1",CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);
//            System.out.println("encryptUserid:"+encryptUserid);

//            String result = testRestful("http://localhost:8080", "/api/custom/irecordset/zpt", null);

//            // Example usage
//            List<String> originalList = new ArrayList<>();
//            for (int i = 1; i <= 2583; i++) {
//                originalList.add(i+"");
//            }
//
//            List<List<String>> splitLists = splitList(originalList, 1000);
//
//            // Print the results
//            for (List<String> sublist : splitLists) {
//                System.out.println("Sublist of size " + sublist.size() + ": " + sublist);
//            }
//            String code = "KI54855844558809";
//            String number = code.substring(code.length() - 1);
//            System.out.println(number);

//            String numberCode = "20240405555563581";
//
//            String dateStrByCode = getDateStrByCode(numberCode);
//            System.out.println(dateStrByCode);

//            String all = "https://www.baizhanveterans.com/download/nginx-1.24.0.tar.gz";
//            String preTitle = getPreTitle(all);
//            String tailTitle = getTailTitle(all);
//            System.out.println(preTitle);
//            System.out.println(tailTitle);

//
//            String yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmsssss").format(new Date());
//            long time = new Date().getTime();
//            String uuid = UUID.randomUUID().toString();
//            String s =  InstructionEnum.SFZYQZX.toString();

//            String htbh = "1,2,3,4,5,6";
//            String[] singleHtbhs = htbh.split(",");
//            List<String> list = Arrays.stream(singleHtbhs).collect(Collectors.toList());
//            System.out.println(list);

            // 示例数值
//            String valueStr = "%E4%B8%9A%E5%8A%A1%E7%B1%BB%E5%9E%8B-ywlx,%E8%B5%84%E9%87%91%E6%9D%A5%E6%BA%90-zjly,%E6%B8%85%E7%AE%97%E6%97%A5%E6%9C%9F-qsrq,%E6%95%B0%E6%8D%AE%E6%9D%A5%E6%BA%90-sjly,%E6%B8%85%E7%AE%97%E9%87%91%E9%A2%9D-qsje";
//
//            String s = String.valueOf((100.00D + 100.00D));
//            System.out.println(s);
//            // 创建 BigDecimal 对象
//            BigDecimal value = new BigDecimal(s);
//
//            // 设置精度并保留两位小数，不使用四舍五入
//            value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
//
//            // 输出结果
//            System.out.println("原始数值: " + s);
//            System.out.println("保留两位小数并添加.00后: " + value);
//
//            String valueStr = "%E8%B4%A2%E5%8A%A1";
////            String fundValue = FormDataUtils.changeNumber(s);
//            String encode = URLDecoder.decode(valueStr, "UTF-8");
//            System.out.println(encode);
//            JSONObject params = new JSONObject();
//            params.put("xb","男");
//            params.put("js","测试");
//            params.put("zjly","1");
//            params.put("mc","");
//            params.put("bz","remark");
//            params.put("zt","1");
//
//            List<JSONObject> detailsParams = new ArrayList<>();
//            JSONObject detailsParam = new JSONObject();
//            detailsParam.put("js","测试details");
//            detailsParam.put("mc","");
//            detailsParam.put("bz","details");
//            detailsParam.put("zt","1");
//            detailsParams.add(detailsParam);
//
//            FormDataUtils.addDetailsData("1", "uf_csbd", "_dt1", detailsParams
//            );

//            String dateString = "2024-08-15"; // 示例日期
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            LocalDate date = LocalDate.parse(dateString, formatter);
//            LocalDate newDate = date.plusDays(90); // 在指定日期上加90天
//            System.out.println("原日期: " + date);
//            String format = newDate.format(formatter);
//            System.out.println("加90天后的日期: " + format);
//            String z = "{\"ptqdrq\":\"2023-07-10\",\"zbdw\":\"\",\"zjly\":\"0\",\"formmodeid\":1000055,\"qsje\":\"-1600.00\",\"yxpthdsqm\":\"2023071014114900149831\",\"ACT_NM\":\"\",\"modedatacreater\":27,\"sjly\":\"0\",\"ywlx\":\"新积分(普通)\",\"qsrq\":\"2024-07-25\",\"zt\":\"0\",\"jbr\":\"\",\"hdjsbs\":\"否\",\"ACT_TOTOL_AT\":\"\"}";
//            JSONObject params = new JSONObject();
//            params.put("xb","男");
//            List<JSONObject> list = new ArrayList<>();
//            JSONObject z = new JSONObject();
//            z.put("status","男");
//            list.add(z);
//
//            params.put("result",list);
//            boolean b = params.containsKey("status");

            String kj = "222255555555556663";
            String substring = kj.substring(0,kj.length() - 1);

            StringBuilder sb = new StringBuilder();
            System.out.println(sb.toString().equals(""));

//            JSONObject result  = new JSONObject();
//            JSONObject oldData = result.getJSONObject("1234");
//            System.out.println(oldData);
//
//            List<String> contractList = new ArrayList<>();
//            contractList.add("1");
//            contractList.add("2");
//            contractList.add("3");
//            String join = String.join(",", contractList);
//            System.out.println(join);

//            JSONObject jsonObject = JSON.parseObject(z);
//            String insert = insert(jsonObject);
//            System.out.println(substring);
//
//            fileCreate("C:\\Users\\sjm\\Desktop\\宋健民-10月报销\\","40 &amp; 41_Rebate &amp; Rebate Payment ADG.xlsx");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static File fileCreate(String fileFoder,String newFileName) {
        File foder = new File(fileFoder);
        File file = new File(fileFoder + newFileName);
        if (!foder.exists()){
            foder.mkdirs();
        }
        if(file.exists()){
            try {
                file.delete();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return file;
    }

    public static String insert(JSONObject jsonObject){
        StringBuilder sql = new StringBuilder();
        sql.append("insert into ").append("uf_qszjmxtz")
                .append("(yxpthdsqm,ACT_NM,ACT_TOTAL_AT,ywlx,zjly,ptqdrq,jbr,zbdw,qsrq,qsje,hdjsbs,sjly," +
                        "zt,modedatacreater,formmodeid)");
        if(jsonObject!=null){
            sql.append(" values ")
                    .append("(")
                    .append("'").append(jsonObject.getString("yxpthdsqm")).append("'").append(",")
                    .append("'").append(jsonObject.getString("ACT_NM")).append("'").append(",")
                    .append(jsonObject.getString("ACT_TOTAL_AT")).append(",")
                    .append("'").append(jsonObject.getString("ywlx")).append("'").append(",")
                    .append(jsonObject.getString("zjly")).append(",")
                    .append("'").append(jsonObject.getString("ptqdrq")).append("'").append(",")
                    .append("'").append(jsonObject.getString("jbr")).append("'").append(",")
                    .append("'").append(jsonObject.getString("zbdw")).append("'").append(",")
                    .append("'").append(jsonObject.getString("qsrq")).append("'").append(",")
                    .append(jsonObject.getString("qsje")).append(",")
                    .append("'").append(jsonObject.getString("hdjsbs")).append("'").append(",")
                    .append(jsonObject.getString("sjly")).append(",")
                    .append(jsonObject.getString("zt")).append(",")
                    .append(jsonObject.getString("modedatacreater")).append(",")
                    .append(jsonObject.getString("formmodeid"))
                    .append(")");
            log.info("清算资金明细台账数据插入sql:"+sql.toString());
        }
        return sql.toString();
    }

    private static String randomSixNumber(){

        // 创建一个随机数生成器
        Random random = new Random();

        // 生成一个六位数的随机整数
        return String.valueOf(random.nextInt(900000) + 100000);

    }

    public static <T> List<List<T>> splitList(List<T> list, int maxSubListSize) {
        List<List<T>> result = new ArrayList<>();
        int totalSize = list.size();

        for (int i = 0; i < totalSize; i += maxSubListSize) {
            int end = Math.min(totalSize, i + maxSubListSize);
            result.add(new ArrayList<>(list.subList(i, end)));
        }

        return result;
    }

    public static String getPreTitle(String furl) {
        String[] split = furl.split(":");
        return split[0];
    }

    public static String getTailTitle(String furl) {
        String[] split = furl.split("\\/");
        return split[split.length - 1];
    }


}
